home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Is this a C BUG??? (A string issue)
- Date: 31 Mar 1996 10:39:11 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4jmjgfINN8pr@keats.ugrad.cs.ubc.ca>
- References: <4jknpf$9k3@abel.cc.sunysb.edu>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4jknpf$9k3@abel.cc.sunysb.edu>,
- George Hauser <ghauser@ic.sunysb.edu> wrote:
- >I am reading the whole line in one shot using fgets(). I need to pad with
- >blank spaces those records that are < 194, until the string is set to 194.
- >
- >Sometimes my records are already filled with 194 and sometimes not.
- >
- >When I get the string of a line that contains 195 chars (data + eoln) it
- >returns a line of 193 and then the next line returns 2 characters....
- >
- >This is WRONG fgets should return 194 characters... but it seems like it
- >finds a NULL on space 193 and then returns the end of line and another null.
-
- No. The 's' in 'fgets' stands for string. Strings must be zero terminated, and
- fgets makes sure of that. When you give it a buffer that is 194 long, it can
- store a string that is no longer than 193. The _size_ of a string is always one
- more than the _length_ of a string to account for the terminating null
- character. Declare the array to be of size 195 if you wish to store strings up
- to 194 long.
-
- >I have spent too much time with this so now even though its ugly I simply
- >check to see if the lenght of the string is greater than 2.
-
- But is this what you really want to do? It's bad programming to write your
- program such that it sets a buffer for the maximum expected line length.
-
- What you are doing could be done better if you read the file one character at a
- time.
-
- store zero to column count
- loop forever
- get character from input file
- if EOF
- break out of loop
- if newline
- increment record count.
- if column count < 194
- write 194-count padding spaces to output file
- store zero to column count
- else if character is not "illegal" and column count <= 194
- write it to output file
- increment column count
- end loop
- if last character was not a newline, increment record count.
-
- >Here's the buggy code.
-
- Your code is a little bit overkill, sorry to say.
-
- When in doubt, process individual characters rather than being clever with
- buffers and string manipulation. It can be more efficient and cleaner.
- The standard IO library already buffers input for you! When you call
- getc(stream), you are typically invoking a fast macro to pull a character out
- of stdio's buffer, replenishing that buffer if necessary.
- --
-
-